package com.hl.config;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.WebExchangeBindException;

import java.util.List;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = WebExchangeBindException.class)
    @ResponseBody
    public String errorHandler(WebExchangeBindException e) {
        for (ObjectError s : e.getAllErrors()) {
            String msg = s.getDefaultMessage();
            assert msg != null;
            if (msg.contains("IllegalArgumentException")) {
                return msg.substring(msg.lastIndexOf(":") + 1);
            }
            return s.getDefaultMessage();
        }
        return e.getMessage();
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String errorHandler(Exception e) {
        e.printStackTrace();
        return "系统错误";
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<String> errorHandler(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        ObjectError objectError = allErrors.stream().findFirst().get();
        return new ResponseEntity<>(objectError.getDefaultMessage(), HttpStatus.BAD_REQUEST);
    }


}
